import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind(("", 8000)) 
s.listen(2)
index = "/index.html"
codes ={"jpeg" 	: "image/jpeg",
	"jpg"	: "image/jpeg",
	"gif"	: "image/gif",
	"css"	: "text/css",
	"html"	: "text/html",
	"htm"	: "text/html",
	"stm"	: "text/html",
	"php"	: "text/html",
	"ico"	: "image/x-icon",
	"py"	: "text/plain"}
	

def statuscode(code,file,found):
	try:
		size = os.path.getsize(file)
	except:
		size = 0
	try:
		status = codes[code]
	except:
		status = "application/octet-stream"
	finally:
		return """HTTP/1.1 %s
Server: PYPHARNO 0.01
Content-Length: %s
Content-Language: de
Content-Type: %s
Connection: close

""" %(found,size,status)
def get(data):
	try:
		openfile = open("."+data,"r")
		print "200 OK"
		return statuscode(data.rsplit(".",1)[1].rsplit("?",1)[0],"."+data,"200 OK") + openfile.read()
		openfile.close()
	except:
		openfile = open("./404.html")
		print "404 FILE NOT FOUND"
		return statuscode(data.rsplit(".",1)[1].rsplit("?",1)[0],"."+data,"404 NOT FOUND") + openfile.read()
		openfile.close()
try: 
	while True: 
		komm, addr = s.accept() 
		while True: 
			data = komm.recv(1024)
			user = []
			data = data.splitlines()
			for i in data:
				i =  i.split(" ",1)
				i[0] = i[0].split(":",0)
				user.append(i)

			a = 0
			for i in user:
				user[a][0] = user[a][0][0]
				#print user[a]
				a+=1
			comm = user[0][0]
			reqf = user[0][1].rsplit()[0]
			para = "false"
			try:
				para = reqf.rsplit("?",1)[1]
				reqf = reqf.rsplit("?",1)[0]
			except:
				pass
			if reqf == "/":
				reqf = index
			elif reqf == "/quit.q":
				s.close()
				sys.exit(1)
			print reqf, " ", para
			if comm == "GET":
				komm.sendall(get(reqf))
				komm.close()
				break
			elif comm == "QUIT":
				s.close()
			else:
				print comm
				komm.close() 
				break

			#print "data:" , data

finally: 
	s.close()
